<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>JSMpeg 多画面播放</title>
    <style type="text/css">
        body {
            margin: 0;
            padding: 24px;
            font-family: Arial, sans-serif;
            background-color: #f5f5f5;
            color: #333;
        }
        h1 {
            margin: 0 0 16px;
            font-size: 24px;
            font-weight: 500;
        }
        #controls {
            margin-bottom: 16px;
            text-align: left;
        }
        button {
            cursor: pointer;
            padding: 8px 12px;
            border-radius: 4px;
            border: 1px solid #1976d2;
            background-color: #2196f3;
            color: #fff;
        }
        button:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }
        #stream-container {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
            gap: 16px;
        }
        .stream-block {
            background-color: #fff;
            border-radius: 8px;
            padding: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            display: flex;
            flex-direction: column;
            gap: 12px;
        }
        .stream-header {
            display: flex;
            gap: 8px;
            align-items: center;
        }
        .stream-header input {
            flex: 1;
            padding: 6px 8px;
            border: 1px solid #ccc;
            border-radius: 4px;
        }
        .stream-actions {
            display: flex;
            gap: 8px;
        }
        .stream-canvas {
            width: 100%;
            background-color: #000;
            border-radius: 4px;
            min-height: 200px;
        }
    </style>
</head>
<body>
<h1>RTSP 多画面播放</h1>
<div id="controls">
    <button id="addStreamBtn">添加画面</button>
</div>
<div id="stream-container"></div>

<template id="stream-template">
    <div class="stream-block">
        <div class="stream-header">
            <input type="text" placeholder="rtsp://用户名:密码@IP:端口/Streaming/Channels/102">
        </div>
        <div class="stream-actions">
            <button class="play-btn">播放</button>
            <button class="stop-btn">停止</button>
        </div>
        <canvas class="stream-canvas"></canvas>
    </div>
</template>

<script type="text/javascript" src="jsmpeg.min.js"></script>
<script type="text/javascript">
    (function () {
        var STREAM_INTERVAL = 58000;
        var streams = [];
        var counter = 0;
        var container = document.getElementById('stream-container');
        var template = document.getElementById('stream-template');
        var addStreamBtn = document.getElementById('addStreamBtn');

        function requestStream(url) {
            return fetch('/stream/play', {
                method: 'POST',
                body: JSON.stringify({url: url}),
                headers: {'Content-Type': 'application/json'}
            }).then(function (response) {
                if (!response.ok) {
                    throw new Error('网络请求失败');
                }
                return response.json();
            }).then(function (res) {
                if (!res || res.code !== 0 || !res.data || !res.data.path) {
                    throw new Error(res && res.msg ? res.msg : '接口返回异常');
                }
                return res.data.path;
            });
        }

        function buildWsUrl(path) {
            var protocol = window.location.protocol === 'https:' ? 'wss://' : 'ws://';
            return protocol + window.location.hostname + ':3000' + path;
        }

        function playStream(stream) {
            var url = (stream.input.value || '').trim();
            if (!url) {
                alert('请输入有效的 RTSP 地址');
                return;
            }
            stream.playBtn.disabled = true;
            requestStream(url).then(function (path) {
                var wsUrl = buildWsUrl(path);
                if (stream.player) {
                    stream.player.destroy();
                    stream.player = null;
                }
                stream.player = new JSMpeg.Player(wsUrl, {canvas: stream.canvas});
                stream.url = url;
                if (stream.keepAliveTimer) {
                    clearInterval(stream.keepAliveTimer);
                }
                stream.keepAliveTimer = setInterval(function () {
                    requestStream(stream.url).catch(function (error) {
                        console.warn('保持拉流失败：' + error.message);
                    });
                }, STREAM_INTERVAL);
            }).catch(function (error) {
                alert('播放失败：' + error.message);
            }).then(function () {
                stream.playBtn.disabled = false;
            });
        }

        function stopStream(stream) {
            if (stream.keepAliveTimer) {
                clearInterval(stream.keepAliveTimer);
                stream.keepAliveTimer = null;
            }
            if (stream.player) {
                stream.player.destroy();
                stream.player = null;
            }
            stream.url = null;
        }

        function addStream(initialUrl) {
            var fragment = document.importNode(template.content, true);
            var element = fragment.querySelector('.stream-block');
            var input = fragment.querySelector('input');
            var playBtn = fragment.querySelector('.play-btn');
            var stopBtn = fragment.querySelector('.stop-btn');
            var canvas = fragment.querySelector('canvas');
            var id = 'stream-' + counter++;

            input.value = initialUrl || '';
            element.setAttribute('data-id', id);

            container.appendChild(fragment);

            var stream = {
                id: id,
                element: element,
                input: input,
                playBtn: playBtn,
                stopBtn: stopBtn,
                canvas: canvas,
                player: null,
                keepAliveTimer: null,
                url: null
            };
            streams.push(stream);

            playBtn.addEventListener('click', function () {
                playStream(stream);
            });
            stopBtn.addEventListener('click', function () {
                stopStream(stream);
            });
        }

        addStreamBtn.addEventListener('click', function () {
            addStream('');
        });

        addStream('rtsp://${username}:${password}@${ip}:${port}/Streaming/Channels/102');
    })();
</script>
</body>
</html>